<template>
  <!-- 主内容区 -->
  <div class="row">
    <!--  左侧树形菜单  -->
    <div class="col-md-4">
      <!--树形菜单上方按钮-->
      <el-button size="small" class="btn btn-primary btn-block margin-bottom" :loading="evaluating" @click="showEvaluationDetail">
        {{bridgeEvaluation.evaluationType !== null && bridgeEvaluation.evaluationType !== undefined?(bridgeEvaluation.evaluationType === 0?('综合评分：'+bridgeEvaluation.sidePoint+' / 技术等级：'+bridgeEvaluation.sideLevel+'类'):'调整项评定：'+bridgeEvaluation.sideLevel+'类'):bridgeEvaluation.sideLevel}}
      </el-button>
      <!--  孔跨列表  -->
      <div class="box box-primary">
        <div class="box-header with-border">
          <h3 class="box-title">孔跨列表</h3>
          <div class="box-tools pull-right" style="margin-top: 5px">
            <!--设置检测的横桥向编号方向-->
            <el-radio-group v-model="direction" @change="handleDirectionChange">
              <el-radio :label="0">左→右</el-radio>
              <el-radio :label="1">右→左</el-radio>
            </el-radio-group>
          </div>
        </div>
        <!--孔跨列表-->
        <el-scrollbar tag="div" class="box-body no-padding" style="height: 100%">
          <el-tree
            v-loading="isTreeLoading"
            ref="tree"
            class="tree-view-scrollable-middle"
            node-key="id"
            :data="siteList"
            :current-node-key="selectedNode.id"
            :render-content="siteTreeRenderContent"
            @node-click="handleNodeClick"
            highlight-current>
          </el-tree>
        </el-scrollbar>
      </div>

      <!--  全桥整体情况  -->
      <div class="box box-warning">
        <div class="box-header with-border">
          <h3 class="box-title">全桥整体情况记录</h3>
          <div v-if="canOperate" class="box-tool pull-right">
            <el-button size="small" @click.prevent="handleBridgeConditionAdd">新增</el-button>
          </div>
        </div>
        <div class="box-body no-padding">
          <el-collapse v-if="bridgeConditionList.length > 0" class="tree-view-scrollable-middle" accordion>
            <el-collapse-item v-for="item of bridgeConditionList" :key="item.id">
              <template slot="title">
                {{getBridgeConditionIntro(item.notes)}}
                <span v-if="canOperate" class="pull-right" style="margin-right: 8px">
                  <el-button size="small" type="default" @click.prevent="handleBridgeConditionEdit(item)">编辑</el-button>
                  <el-button size="small" type="danger" @click.prevent="handleDelete(item)">删除</el-button>
                </span>
              </template>
              <div>{{item.notes}}</div>
              <div>
                <DiseasePhotoWall
                  :canOperate="canOperate"
                  :defaultList="item.diseasePhotoList"
                  :imageUrl="rootUrl+'/getMediumDiseasePhoto'"
                  :thumbnailUrl="rootUrl+'/getMiniDiseasePhoto'"
                  :uploadUrl="rootUrl+'/addDiseasePhoto'"
                  :deleteUrl="rootUrl+'/deleteDiseasePhoto'"
                  :uploadParam="item">
                </DiseasePhotoWall>
              </div>
            </el-collapse-item>
          </el-collapse>
          <div v-else style="text-align: center;padding: 8px 8px;">暂无数据</div>
        </div>
      </div>
    </div>

    <!--病害表格-->
    <div class="col-md-8">
      <!--病害列表-->
      <Table
        v-loading="isTableLoading"
        :title="currentSide.roadNo + ' ' + currentSide.stakeNo + ' ' +currentSide.bridgeName + ' / ' +currentSide.sideTypeName"
        searchHint="输入关键字查找，多个关键字用空格隔开"
        :pageData="filterDiseasePageData"
        :rowClassName="setRowClassName"
        :stripe="false"
        @search="search"
        @sizeChange="pageSizeChange"
        @pageTurning="pageTurning"
        @filterChange="filterChange">

        <!--展开照片列表-->
        <el-table-column type="expand">
          <template slot-scope="scope">
            <DiseasePhotoWall
              :canOperate="canOperate"
              :defaultList = "scope.row.diseasePhotoList"
              :imageUrl="rootUrl+'/getMediumDiseasePhoto'"
              :thumbnailUrl="rootUrl+'/getMiniDiseasePhoto'"
              :uploadUrl="rootUrl+'/addDiseasePhoto'"
              :deleteUrl="rootUrl+'/deleteDiseasePhoto'"
              :uploadParam="scope.row"
              @onClose="photoList=>scope.row.diseasePhotoList=photoList">
            </DiseasePhotoWall>
          </template>
        </el-table-column>

        <!--表格列-->
        <el-table-column v-for="col of columns"
                         :align="col.align"
                         :key="col.prop"
                         :column-key="col.prop"
                         :prop="col.prop"
                         :label="col.label"
                         :width="col.width"
                         :sortable="col.sortable"
                         :filters="col.filters">
        </el-table-column>

        <!--数据操作按钮组-->
        <el-table-column v-if="canOperate" label="操作" align="center" width="170">
          <template slot-scope="scope">
            <el-button size="mini" @click="handleDiseaseEdit(scope.row)">编辑</el-button>
            <el-button size="mini" type="success" @click="handleDiseaseCopy(scope.row)">复制</el-button>
            <el-button size="mini" type="danger" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>

        <!--表格上方的按钮区-->
        <template slot="buttonArea">
          <template v-if="canOperate">
            <el-button size="mini" @click="handlePointAdjustment" style="margin-right: 8px;">评定方式选择</el-button>
            <el-button size="mini" @click="handleBridgeSiteConditionAdd" style="margin-right: 8px;">孔跨情况记录</el-button>
            <el-button size="mini" @click="handleDiseaseAdd(SUPER)">上部结构病害</el-button>
            <el-button size="mini" @click="handleDiseaseAdd(SUB)">下部结构病害</el-button>
            <el-button size="mini" @click="handleDiseaseAdd(DECK)">桥面系病害</el-button>
          </template>
          <el-button size="mini" class="pull-right" style="margin-bottom: 5px;" @click="handleBack"><i class="fa fa-chevron-left"></i>&nbsp;&nbsp;返回</el-button>
        </template>

        <!--颜色标注说明-->
        <template slot="footer">
          <span class="color-tip title">颜色标注：</span>
          <span class="color-tip missing">构件缺失</span>
          <span class="color-tip info-row">标度3</span>
          <span class="color-tip warning-row">标度4</span>
          <span class="color-tip danger-row">标度5</span>
          <span class="color-tip significant-row">重点关注</span>
        </template>
      </Table>
    </div>

    <!--桥梁整体状况描述对话框-->
    <el-dialog title="桥梁整体情况记录" size="tiny" v-model="isBridgeConditionDialogVisible" :close-on-click-modal="false">
      <el-form :model="bridgeConditionForm" :rules="bridgeConditionRules" ref="bridgeConditionForm">
        <el-form-item prop="notes">
          <el-input type="textarea" placeholder="请输入桥梁整体情况" v-model="bridgeConditionForm.notes"></el-input>
        </el-form-item>
      </el-form>
      <!--对话框按钮-->
      <div slot="footer" class="dialog-footer">
        <el-button @click="isBridgeConditionDialogVisible=false">取消</el-button>
        <el-button type="primary" @click="updateBridgeCondition" :loading="isBridgeConditionUpdating">确定</el-button>
      </div>
    </el-dialog>

    <!--桥梁构件病害记录-->
    <el-dialog :title="diseaseDialogTitle+'病害记录'" size="tiny" v-model="isDiseaseDialogVisible" :close-on-click-modal="false">
      <el-form :model="diseaseForm" :rules="diseaseRules" ref="diseaseForm" v-loading="isDiseaseFormLoading" label-width="160px">
        <!--孔号-->
        <el-form-item label="孔号" prop="siteNo">
          <el-input-number v-model="diseaseForm.siteNo" style="width: 100%;" :min="1" :max="siteList.length" @change="handleSiteChange"></el-input-number>
        </el-form-item>
        <template v-if="!justSite">
          <!--构件类型-->
          <el-form-item label="构件类型" prop="bridgePartsId">
            <el-select v-model="diseaseForm.bridgePartsId" style="width: 100%;" placeholder="请选择构件类型，输入文字可搜索" @change="handlePartsChange" filterable>
              <el-option v-for="item of bridgePartsList" :key="item.id" :label="item.memberTypeName" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
          <!--构件编号-->
          <el-form-item v-if="diseaseUpdateType === 'EDIT'" label="构件编号" prop="bridgeMemberId">
            <el-select key="bridgeMemberId" v-model="diseaseForm.bridgeMemberId" style="width: 100%" placeholder="请选择构件编号，输入文字可搜索" @change="handleMemberChange" filterable>
              <el-option v-for="item of bridgeMemberList" :key="item.id" :label="item.bridgeMemberName" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
          <!--构件编号-->
          <el-form-item v-if="diseaseUpdateType === 'ADD' || diseaseUpdateType === 'COPY'" label="构件编号" prop="bridgeMemberIds">
            <el-select key="bridgeMemberIds" v-model="diseaseForm.bridgeMemberIds" style="width: 100%" placeholder="请选择构件编号，可多选，输入文字可搜索" multiple filterable>
              <el-option v-for="item of bridgeMemberList" :key="item.id" :label="item.bridgeMemberName" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
          <!--病害类型-->
          <el-form-item label="病害类型" prop="diseaseTypeId">
            <el-select v-model="diseaseForm.diseaseTypeId" style="width: 100%;" placeholder="请选择病害类型，输入文字可搜索" @change="handleDiseaseChange" filterable>
              <el-option v-for="item of diseaseTypeList" :key="item.id" :label="item.name" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
          <!--病害描述方式-->
          <el-form-item label="描述方式" prop="diseaseDescId">
            <el-select v-model="diseaseForm.diseaseDescId" style="width: 100%;" placeholder="请选择病害描述方式，输入文字可搜索" @change="handleDiseaseDescChange" filterable>
              <el-option v-for="item of diseaseDescList" :key="item.id"
                         :label="item.diseaseDesc.replace(new RegExp('\\{.*?\\}', 'g'), '_').replace(new RegExp('[\\[\\]]', 'g'), '')"
                         :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
          <!--病害描述参数——纵桥向位置-->
          <el-form-item v-if="diseaseDescParam.containLPosition" :label="diseaseDescParam.containLPositionRange ? '距小桩号墩台起始距离' : '距小桩号墩台距离'">
            <el-input type="number" v-model.number="diseaseForm.lPositionStart" placeholder="单位：m"></el-input>
          </el-form-item>
          <el-form-item v-if="diseaseDescParam.containLPositionRange" label="距小桩号墩台结束距离">
            <el-input type="number" v-model.number="diseaseForm.lPositionEnd" placeholder="单位：m"></el-input>
          </el-form-item>
          <!--病害描述参数——横桥向位置---->
          <el-form-item v-if="diseaseDescParam.containHPosition" :label="diseaseDescParam.containHPositionRange ? '距左缘起始距离' : '距左缘距离'">
            <el-input type="number" v-model.number="diseaseForm.hPositionStart" placeholder="单位：m"></el-input>
          </el-form-item>
          <el-form-item v-if="diseaseDescParam.containHPositionRange" label="距左缘结束距离">
            <el-input type="number" v-model.number="diseaseForm.hPositionEnd" placeholder="单位：m"></el-input>
          </el-form-item>
          <!--病害描述参数——垂直位置-->
          <el-form-item v-if="diseaseDescParam.containVPosition" :label="diseaseDescParam.containVPositionRange ? '距上缘起始距离' : '距上缘距离'">
            <el-input type="number" v-model.number="diseaseForm.vPositionStart" placeholder="单位：m"></el-input>
          </el-form-item>
          <el-form-item v-if="diseaseDescParam.containVPositionRange" label="距上缘结束距离">
            <el-input type="number" v-model.number="diseaseForm.vPositionEnd" placeholder="单位：m"></el-input>
          </el-form-item>
          <!--病害描述参数——构件空间部位-->
          <el-form-item v-if="diseaseDescParam.containPosition" label="构件部位">
            <el-select v-model="diseaseForm.position" style="width: 100%;" placeholder="请选择构件部位，输入文字可搜索" filterable>
              <el-option v-for="item of memberPositionList" :key="item.id" :label="item.name" :value="item.name"></el-option>
            </el-select>
          </el-form-item>
          <!--病害描述参数——病害数量-->
          <el-form-item v-if="diseaseDescParam.containCount" label="病害数量" prop="count">
            <el-input-number v-model="diseaseForm.count" style="width: 100%;" :min="0"></el-input-number>
          </el-form-item>
          <!--病害描述参数——病害角度-->
          <el-form-item v-if="diseaseDescParam.containAngle" :label="angleLabel">
            <el-input type="number" v-model.number="diseaseForm.angle" placeholder="请输入角度"></el-input>
          </el-form-item>
          <!--最小长度-->
          <el-form-item v-if="diseaseDescParam.containMinLength" :label="minLengthLabel">
            <el-input type="number" v-model.number="diseaseForm._minLength" placeholder="请输入长度"></el-input>
          </el-form-item>
          <!--最大长度-->
          <el-form-item v-if="diseaseDescParam.containMaxLength" :label="maxLengthLabel">
            <el-input type="number" v-model.number="diseaseForm._maxLength" placeholder="请输入长度"></el-input>
          </el-form-item>
          <!--最小宽度-->
          <el-form-item v-if="diseaseDescParam.containMinWidth" :label="minWidthLabel">
            <el-input type="number" v-model.number="diseaseForm._minWidth" placeholder="请输入宽度"></el-input>
          </el-form-item>
          <!--最大宽度-->
          <el-form-item v-if="diseaseDescParam.containMaxWidth" :label="maxWidthLabel">
            <el-input type="number" v-model.number="diseaseForm._maxWidth" placeholder="请输入宽度"></el-input>
          </el-form-item>
          <!--最小深度-->
          <el-form-item v-if="diseaseDescParam.containMinDepth" :label="minDepthLabel">
            <el-input type="number" v-model.number="diseaseForm._minDepth" placeholder="请输入深度"></el-input>
          </el-form-item>
          <!--最大深度-->
          <el-form-item v-if="diseaseDescParam.containMaxDepth" :label="maxDepthLabel">
            <el-input type="number" v-model.number="diseaseForm._maxDepth" placeholder="请输入深度"></el-input>
          </el-form-item>
          <!--程度描述-->
          <el-form-item v-if="diseaseDescParam.containPercentDegree" :label="percentDegreeLabel" prop="percentDegree">
            <el-input-number v-model="diseaseForm.percentDegree" style="width: 100%;" :min="0" :max="100"></el-input-number>
          </el-form-item>
          <!--程度描述，文字-->
          <el-form-item v-if="diseaseDescParam.containDescDegree" label="程度描述">
            <el-select v-model="diseaseForm.descDegree" style="width: 100%;" placeholder="请选择病害程度" filterable>
              <el-option v-for="item of descDegreeList" :key="item.id" :label="item.name" :value="item.name"></el-option>
            </el-select>
          </el-form-item>
          <!--性状描述-->
          <el-form-item v-if="diseaseDescParam.containBehaviorDesc" label="性状描述">
            <el-input v-model="diseaseForm.behaviorDesc" placeholder="请输入病害性状描述"></el-input>
          </el-form-item>
          <!--扣分标度-->
          <el-form-item label="扣分标度">
            <el-select v-model="diseaseForm.deductionScale" style="width: 100%" placeholder="请选择扣分标度，默认为标度2">
              <el-option v-for="item in (!!recordDiseaseType?recordDiseaseType.maxScale:0)" :key="item" :label="'标度'+item" :value="item"></el-option>
            </el-select>
          </el-form-item>
          <!--是否为重点关注病害-->
          <el-form-item label="重点关注病害">
            <el-switch v-model="diseaseForm.isSignificant" on-text="是" off-text="否" :on-value="1" :off-value="0"></el-switch>
          </el-form-item>
        </template>
        <!--备注-->
        <el-form-item label="备注">
          <el-input type="textarea" v-model="diseaseForm.notes" placeholder="请输入备注信息"></el-input>
        </el-form-item>
      </el-form>
      <!--对话框按钮-->
      <div slot="footer" class="dialog-footer">
        <el-button @click="isDiseaseDialogVisible=false">取消</el-button>
        <el-button type="primary" @click="updateBridgeDisease" :loading="isBridgeDiseaseUpdating">确定</el-button>
      </div>
    </el-dialog>

    <!--评定信息查看表格-->
    <el-dialog title="桥梁评分详表" size="large" v-model="isEvaluationDetailDialogVisible">
      <div v-if="!evaluationDetail || evaluationDetail.length===0" class="el-table__empty-block" style="width: 100%"  v-loading="loadingEvaluationTable" element-loading-text="正在加载评定信息">
        <span class="el-table__empty-text" style="width: 100%;">暂无详细评定信息</span>
      </div>
      <el-tabs v-else>
        <el-tab-pane v-for="structure of evaluationDetail" :key="structure.superstructureTypeName" :label="structure.superstructureTypeName">
          <!--部构件表格区域-->
          <div class="el-table el-table--fit el-table--striped el-table--border el-table--enable-row-hover el-table--enable-row-transition">
            <!--表格标题-->
            <div class="el-table__header-wrapper">
              <table cellspacing="0" cellpadding="0" border="0" class="el-table__header" style="width:100%; font-size: 1em; line-height: 1.2em;">
                <thead>
                <tr>
                  <th class="is-center">部位</th>
                  <th class="is-center">部件</th>
                  <th class="is-center">权重</th>
                  <th class="is-center">重分配权重</th>
                  <th class="is-center">构件类型</th>
                  <th class="is-center">构件数量</th>
                  <th class="is-center">孔跨</th>
                  <th class="is-center">构件</th>
                  <th class="is-center" style="width: 200px;">评定指标</th>
                  <th class="is-center">标度</th>
                  <th class="is-center">扣分值</th>
                  <th class="is-center">构件得分</th>
                  <th class="is-center">部件得分</th>
                  <th class="is-center">部位得分</th>
                  <th class="is-center">总分</th>
                  <th class="is-center">评级</th>
                </tr>
                </thead>
              </table>
            </div>
            <!--表格主体-->
            <div class="el-table__body-wrapper">
              <table cellspacing="0" cellpadding="0" border="0" class="el-table__body" style="width:100%; font-size: 1em; line-height: 1.2em;">
                <tbody>
                <tr v-for="(item, index, array) in mixEvaluationDto(structure.positionEvaluationList)" :key="index">
                  <td v-if="item.positionTypeName !== undefined" class="is-center" :rowspan="item.positionRowSpan">{{item.positionTypeName}}</td>
                  <td v-if="item.partsTypeName !== undefined" class="is-center" :rowspan="item.partsRowSpan">{{item.partsTypeName}}</td>
                  <td v-if="item.originalWeight !== undefined" class="is-center" :rowspan="item.partsRowSpan">{{item.originalWeight}}</td>
                  <td v-if="item.resizeWeight !== undefined" class="is-center" :rowspan="item.partsRowSpan">{{item.resizeWeight}}</td>
                  <td v-if="item.memberTypeName !== undefined" class="is-center" :rowspan="item.memberTypeRowSpan">{{item.memberTypeName}}</td>
                  <td v-if="item.memberCount !== undefined" class="is-center" :rowspan="item.memberTypeRowSpan">{{item.memberCount}}</td>
                  <td v-if="item.siteNo !== undefined" class="is-center" :rowSpan="item.siteRowSpan">{{item.siteNo}}</td>
                  <td v-if="item.bridgeMemberName !== undefined" class="is-center" :rowspan="item.bridgeMemberRowSpan">{{item.bridgeMemberName}}</td>
                  <td class="is-center" style="width: 200px;">{{item.evaluationIndexName}}</td>
                  <td class="is-center">{{item.deductionScale}}</td>
                  <td class="is-center">{{item.deductionPoint}}</td>
                  <td v-if="item.bridgeMemberName !== undefined" class="is-center" :rowspan="item.bridgeMemberRowSpan">{{item.bridgeMemberPoint}}</td>
                  <td v-if="item.partsPoint !== undefined" class="is-center" :rowspan="item.partsRowSpan">{{item.partsPoint}}</td>
                  <td v-if="item.positionPoint !== undefined" class="is-center" :rowspan="item.positionRowSpan">{{item.positionPoint}}</td>
                  <td v-if="index === 0" class="is-center" :rowspan="structure.rowSpan">{{structure.point}}</td>
                  <td v-if="index === 0" class="is-center" :rowspan="structure.rowSpan">{{structure.level+'类'}}</td>
                </tr>
                </tbody>
              </table>
            </div>
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-dialog>

    <!-- 评分调整项对话框 -->
    <el-dialog title="评分调整" size="tiny" v-model="isAdjustPointDialogVisible">
      <el-select v-model="evaluationType" style="width: 100%;" placeholder="请选择评分调整项" clearable>
        <el-option key="0" label="综合评定" :value="0"></el-option>
        <el-option key="1" label="5类桥梁技术状况单项控制指标" :value="1"></el-option>
        <el-option key="2" label="当上部结构和下部结构技术状况等级为3类、桥面系技术状况等级为4类，且桥梁总体技术状况等级为4类时，桥梁总体技术状况等级可评定为3类" :value="2"></el-option>
        <el-option key="3" label="当主要部件评分达到4类或5类且影响桥梁安全时，可按照桥梁主要部件最差缺损状况评定" :value="3"></el-option>
      </el-select>
      <!--对话框按钮-->
      <div slot="footer" class="dialog-footer">
        <el-button @click="isAdjustPointDialogVisible=false">取消</el-button>
        <el-button type="primary" @click="adjustPoint">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import Table from "../../components/content/bridge/Table.vue";
  import DiseasePhotoWall from "../template/DiseasePhotoWall.vue";
  import {doDelete, doGet, doPost} from "../../assets/js/utils/RequestUtils";
  import {getAuthorizedFunction} from "../../assets/js/global";
  import {ADD, COPY, DELETE, EDIT, MANAGE} from "../../assets/js/enum/FunctionType";
  import {DECK, SUB, SUPER} from "../../assets/js/enum/PositionType";
  import {clearFields, equals, nvl} from "../../assets/js/utils/ObjectUtils";
  import {ANGLE, BEHAVIOR_DESC,COUNT, DESC_DEGREE,H_POSITION_END,H_POSITION_START,L_POSITION_END,L_POSITION_START, MAX_DEPTH,
    MAX_LENGTH,MAX_WIDTH,MIN_DEPTH,MIN_LENGTH,MIN_WIDTH,PERCENT_DEGREE,POSITION,V_POSITION_END,V_POSITION_START} from "../../assets/js/enum/DiseaseParam";
  import {intValidator} from "../../assets/js/utils/ValidateUtils";
  import {getDeductionPoint, pointToLevel, mixEvaluationDto} from "../../assets/js/utils/EvaluationUtils";
  import {convertUnit} from "../../assets/js/utils/DiseaseUtils";
  import {MM} from "../../assets/js/enum/DimensionUnits";
  import {ASCENDING, DESCENDING} from "../../assets/js/enum/SortType";

  //桥梁部件检查，用于更换孔号后，判断新孔是否存在此构件类型
  const BRIDGE_PARTS_CHECK_URL = "/checkBridgeParts";
  //桥梁构件检查，作用同上
  const BRIDGE_MEMBER_CHECK_URL = "/checkBridgeMember";
  //检查桥梁构件数组，作用同上
  const BRIDGE_MEMBERS_CHECK_URL = "/checkBridgeMembers";
  //删除病害的地址
  const DELETE_URL = "/deleteBridgeDisease";
  //新增病害地址
  const ADD_DISEASE_URL = "/addBridgeDisease";
  //编辑病害地址
  const EDIT_DISEASE_URL = "/editBridgeDisease";
  //桥梁评定的地址
  const BRIDGE_EVALUATION_URL = "/evaluate";
  //获取详细评定结果表格数据
  const EVALUATION_DETAIL_URL = "/getEvaluationDetail";
  //评分调整地址
  const ADJUST_POINT_URL = "/adjustPoint";

  //桥梁整体情况记录标题字数
  const BRIDGE_CONDITION_TITLE_SIZE = 10;

  //桥梁整体状况记录表单
  const BRIDGE_CONDITION_FORM = "bridgeConditionForm";
  //病害记录表单
  const DISEASE_FORM = "diseaseForm";

  export default {
    name:"TaskBridgeDisease",
    props:{
      //当前任务单
      currentTask:{
        type:Object,
        required:true
      },
      //当前操作的分幅
      currentSide:{
        type:Object,
        required:true
      },
      //根路径，因为任务单分为经常、定期及特殊检查，根路径是动态的，所以由任务单传入
      rootUrl:{
        type:String,
        required:true
      }
    },
    data() {
      /** 部件校验器，用于判断切换后的孔跨是否存在该部件 */
      let bridgePartsValidator = (rules, value, callback)=>{
        doGet(this.rootUrl+BRIDGE_PARTS_CHECK_URL, {
          data:{
            id:value,
            bridgeId:this.diseaseForm.bridgeId,
            sideTypeId:this.diseaseForm.sideTypeId,
            siteNo:this.diseaseForm.siteNo
          },
          component:this
        }).then(response=>{
          if(response.content) callback();
          else callback(new Error("该跨不存在与原病害材料类型、构件类型一致的构件类型"));
        }).catch(error=>callback(new Error("网络故障，校验失败")))
      };

      /** 构件校验器，用于判断切换后的孔跨是否包含该构件 */
      let bridgeMemberValidator = (rules, value, callback)=>{
        doGet(this.rootUrl+BRIDGE_MEMBER_CHECK_URL, {
          data:{
            id:value,
            bridgeId:this.diseaseForm.bridgeId,
            sideTypeId:this.diseaseForm.sideTypeId,
            siteNo:this.diseaseForm.siteNo
          },
          component:this
        }).then(response=>{
          if(response.content) callback();
          else callback(new Error("该跨不存在此构件"));
        }).catch(error=>callback(new Error("网络故障，校验失败")))
      };

      /** 桥梁构件多选框校验 */
      let bridgeMembersValidator = (rules, value, callback)=>{
        doGet(this.rootUrl+BRIDGE_MEMBERS_CHECK_URL, {
          data:{
            ids:value,
            bridgeId:this.diseaseForm.bridgeId,
            sideTypeId:this.diseaseForm.sideTypeId,
            siteNo:this.diseaseForm.siteNo
          },
          component:this
        }).then(response=>{
          if(response.content) callback();
          else callback(new Error("该跨不存在此构件"));
        }).catch(error=>callback(new Error("网络故障，校验失败")))
      };

      return {
        //病害列表是否加载中
        isTableLoading:false,
        //孔跨列表是否加载中
        isTreeLoading:false,
        //孔跨数据
        siteList:[],
        //选中的孔跨
        selectedNode:{},
        //病害表格数据
        diseasePageData:{
          data:[],
          pageSize:10,
          currentPage:1
        },
        //搜索字符串
        searchStr:"",
        //表格列
        columns:[
          {prop:"siteNo", label:"孔号", width:"90", align:"center", sortable:true},
          {prop:"bridgeMemberName", label:"构件", width:"130", align:"center", sortable:true, filters:[{text:"缺失", value:0}]},
          {prop:"bridgeDiseaseName", label:"病害描述", align:"left"},
          {prop:"deductionScale", label:"标度", width:"90", align:"center", filters:[{text:"标度1", value:1},{text:"标度2", value:2},{text:"标度3", value:3},{text:"标度4", value:4},{text:"标度5", value:5},{text:"重点关注", value:0}]}
        ],
        //用于表格搜索的属性字段
        searchProps:["partsTypeName", "bridgeMemberName", "diseaseTypeName", "bridgeDiseaseName"],
        //排序属性
        sortProp:{
          prop:"",
          order:ASCENDING
        },
        //过滤属性
        filters:{prop:"", values:[]},
        //桥梁整体状况记录集合
        bridgeConditionList:[],
        //桥梁整体状况记录对话框是否可见
        isBridgeConditionDialogVisible:false,
        //桥梁整体状况记录表单
        bridgeConditionForm:{},
        //桥梁整体状况记录表单校验规则
        bridgeConditionRules:{
          notes:[{required:true, message:"请输入桥梁整体情况说明", trigger:"blur"}]
        },
        //桥梁整体状况表单是否正在添加
        isBridgeConditionUpdating:false,
        //桥梁整体状况更新类型，新增还是编辑
        bridgeConditionUpdateType:"",
        //是否为整跨情况记录
        justSite:false,
        //检测的方向，0-从左往右，1-从右往左
        direction:0,
        //病害记录对话框是否可见
        isDiseaseDialogVisible:false,
        //病害表单是否正在加载中
        isDiseaseFormLoading:false,
        //病害表单对话框标题
        diseaseDialogTitle:"",
        //病害更新类型，新增、编辑或复制
        diseaseUpdateType:"",
        //病害表单
        diseaseForm:{
          //孔号
          siteNo:1,
          //某座桥的部件，不是部件类型
          bridgePartsId:"",
          //某座桥的构件，不是构件类型
          bridgeMemberId:"",
          //某座桥的构件集合，考虑多个构件同一个病害的情况
          bridgeMemberIds:[],
          //病害类型
          diseaseTypeId:"",
          //病害描述ID
          diseaseDescId:"",
          //病害描述规则
          diseaseDesc:"",
          //横桥向起始位置
          hPositionStart:null,
          //横桥向范围
          hPositionEnd:null,
          //纵桥向起始位置
          lPositionStart:null,
          //纵桥向范围
          lPositionEnd:null,
          //垂直向起始位置
          vPositionStart:null,
          //垂直向范围
          vPositionEnd:null,
          //构件的部位
          position:"",
          //病害数量
          count:"",
          //病害角度
          angle:"",
          //最小长度，用于页面表单展示，上传至服务器是会将单位转换为mm赋予新属性minLength
          _minLength:"",
          //最大长度，同上
          _maxLength:"",
          //最小宽度，同上
          _minWidth:"",
          //最大宽度，同上
          _maxWidth:"",
          //最小深度，同上
          _minDepth:"",
          //最大深度，同上
          _maxDepth:"",
          //百分比程度描述
          percentDegree:"",
          //文字程度描述
          descDegree:"",
          //性状描述
          behaviorDesc:"",
          //备注
          notes:"",
          //是否为重点关注病害
          isSignificant:"",
          //扣分标度
          deductionScale:"",
          //扣分值
          deductionPoint:""
        },
        //病害表单校验规则
        diseaseRules:{
          siteNo:[
            {required:true, type:"number", message:"请输入孔号", trigger:"blur"},
            {validator:intValidator, trigger:"blur"}
          ],
          bridgePartsId:[
            {required:true, message:"请选择构件类型", trigger:"blur"},
            {validator:bridgePartsValidator, trigger:"blur"}
          ],
          bridgeMemberId:[
            {required:true, message:"请选择构件编号", trigger:"blur"},
            {validator:bridgeMemberValidator, trigger:"blur"}
          ],
          bridgeMemberIds:[
            {required:true, type:"array", message:"请选择构件编号", trigger:"blur"},
            {validator:bridgeMembersValidator, trigger:"blur"}
          ],
          diseaseTypeId:[
            {required:true, message:"请选择病害类型", trigger:"blur"}
          ],
          diseaseDescId:[
            {required:true, message:"请选择病害描述方式", trigger:"blur"}
          ],
          count:[
            {validator:intValidator, trigger:"blur"}
          ],
          percentDegree:[
            {validator:intValidator, trigger:"blur"}
          ]
        },
        //桥梁部件数组
        bridgePartsList:[],
        //桥梁构件数组
        bridgeMemberList:[],
        //病害类型数组
        diseaseTypeList:[],
        //病害描述类型数组
        diseaseDescList:[],
        //记录的桥梁部位
        recordPosition:"",
        //正在记录的病害类型
        recordDiseaseType:{maxScale:0},
        //表单是否上传中
        isBridgeDiseaseUpdating:false,
        //病害描述参数，用于表单输入项的隐藏与否
        diseaseDescParam: {
          containHPosition: false,
          containHPositionRange: false,
          containLPosition: false,
          containLPositionRange: false,
          containVPosition: false,
          containVPositionRange: false,
          containPosition:false,
          containCount:false,
          containAngle:false,
          containMinLength:false,
          containMaxLength:false,
          containMinWidth:false,
          containMaxWidth:false,
          containMinDepth:false,
          containMaxDepth:false,
          containPercentDegree:false,
          containDescDegree:false,
          containBehaviorDesc:false
        },
        //构件部位描述数组
        memberPositionList:[],
        //程度描述数组
        descDegreeList:[],
        //当前桥梁评分
        bridgeEvaluation:{sidePoint:"正在评定"},
        //是否正在评定
        evaluating:false,
        //打开详细评定结果
        isEvaluationDetailDialogVisible:false,
        //加载评定结果表格
        loadingEvaluationTable:false,
        //评定结果数据
        evaluationDetail:[],
        //评分调整项对话框
        isAdjustPointDialogVisible:false,
        //评分调整项
        evaluationType:"",
        //其他常量，桥梁部位等
        SUPER,
        SUB,
        DECK
      }
    },
    computed: {
      //数据查询参数，用于查询部构件等
      queryParam() {
        return {
          taskId:this.currentTask.id,
          bridgeId:this.currentSide.bridgeId,
          sideTypeId:this.currentSide.sideTypeId,
          direction:this.direction
        }
      },
      //过滤后的病害分页数据
      filterDiseasePageData() {
        let result = {
          pageSize: this.diseasePageData.pageSize,
          currentPage: this.diseasePageData.currentPage
        };

        let filterData = this.diseasePageData.data;

        if(Array.isArray(filterData)) {
          //选中孔跨过滤
          if (this.selectedNode.id) filterData = filterData.filter(item=>item.siteNo === this.selectedNode.siteNo);
          //搜索框过滤
          filterData = filterData
            .filter(item=>this.searchStr.split(" ")
              .every(str=>this.searchProps.length === 0 || this.searchProps.some(prop=>!!item[prop] && item[prop].includes(str))));
          //筛选
          if(!!this.filters.prop && this.filters.values.length > 0) {
            //判断是否筛选的是构件缺失的病害
            if(this.filters.prop === "bridgeMemberName") {
              filterData = filterData.filter(item=>!item.bridgeMemberId);
            } else {
              if (this.filters.values.includes(0)) filterData = filterData.filter(item => this.filters.values.includes(item[this.filters.prop]) || item.isSignificant === 1);
              else filterData = filterData.filter(item => this.filters.values.includes(item[this.filters.prop]));
            }
          }
          //排序
          if(!!this.sortProp.prop) {
            if (this.sortProp.order === DESCENDING) {
              Array.sort(filterData, (data1, data2) => data2[this.sortProp.prop] - data1[this.sortProp.prop]);
            } else {
              Array.sort(filterData, (data1, data2) => data1[this.sortProp.prop] - data2[this.sortProp.prop]);
            }
          }
        }
        //分页
        result.total = filterData.length;
        result.data = filterData.slice(
          (result.currentPage - 1) * result.pageSize,
          (result.currentPage) * result.pageSize
        );
        //返回结果
        return result;
      },
      //对应表单控件的label标签
      angleLabel() {
        return "角度(°)";
      },
      //对应表单控件的label标签
      minLengthLabel() {
        let label = "长度";
        if(this.diseaseDescParam.containMaxLength) label = "最小长度";
        return label + "(" + this.parseUnit(MIN_LENGTH) + ")";
      },
      //对应表单控件的label标签
      maxLengthLabel() {
        return "最大长度(" + this.parseUnit(MAX_LENGTH) + ")";
      },
      //对应表单控件的label标签
      minWidthLabel() {
        let label = "宽度";
        if(this.diseaseDescParam.containMaxWidth) label = "最小宽度";
        return label + "(" + this.parseUnit(MIN_WIDTH) + ")";
      },
      //对应表单控件的label标签
      maxWidthLabel() {
        return "最大宽度(" + this.parseUnit(MAX_WIDTH) + ")";
      },
      //对应表单控件的label标签
      minDepthLabel() {
        let label = "深度";
        if(this.diseaseDescParam.containMaxDepth) label = "最小深度";
        return label + "(" + this.parseUnit(MIN_DEPTH) + ")";
      },
      //对应表单控件的label标签
      maxDepthLabel() {
        return "最大深度(" + this.parseUnit(MAX_DEPTH) + ")";
      },
      //对应表单控件的label标签
      percentDegreeLabel() {
        return "百分比程度(" + this.parseUnit(PERCENT_DEGREE) + ")";
      },
      //是否能新增
      canOperate() {
        //管理员除非已经通过审核，否则一直可以修改病害
        let isManager = this.$store.state.User.currentUser.id === this.currentTask.manager;
        if(isManager && this.currentSide.status < 2) return true;
        else return !isManager && this.currentSide.status < 1;
      },
    },
    methods:{
      //返回上一级页面
      handleBack() {
        this.$emit("onBack");
      },
      //孔跨列表的显示的内容自定义，使用vue的render函数
      siteTreeRenderContent(h, {node, data, store}) {
        return h('span', {style:"display:inline-block;width:90%;overflow:hidden;"},[
          h('span', {}, [data.siteName]),
          h('span', {style:"float:right;margin-right:8px"}, [h('el-tag', {style:"text-align:center",props:{type:(data.maxScale>3 || data.significantCount>0?"danger":"gray")}}, [data.diseaseCount])]),
          h('span', {style:"float:right;margin-right:8px"}, [h('el-tag', {style:"text-align:center",props:{type:"success"}}, [!!data.jointNo?"第"+data.jointNo+"联":"未分联"])]),
          h('span', {style:"float:right;margin-right:8px"}, [h('el-tag', {style:"text-align:center",props:{type:"primary"}}, [!!data.superstructureTypeName?data.superstructureTypeName:"无结构类型"])])
        ]);
      },
      //响应孔跨的点击事件
      handleNodeClick(data, node, nodeList) {
        if(this.selectedNode === data) {
          //还原孔号及选中的节点
          this.selectedNode = {};
          this.diseaseForm.siteNo = 1;
          //取消选择
          node.store.currentNode = null;
        } else {
          //设置选中的节点及孔号
          this.selectedNode = data;
          this.diseaseForm.siteNo = data.siteNo;
        }
        this.diseasePageData.currentPage = 1;
      },
      //表格搜索
      search(searchStr) {
        this.searchStr = searchStr;
      },
      //表格过滤
      filterChange(filters) {
        this.filters = filters;
      },
      //表格尺寸修改
      pageSizeChange(newSize) {
        this.diseasePageData.pageSize = newSize;
      },
      //表格换页
      pageTurning(curPage) {
        this.diseasePageData.currentPage = curPage;
      },
      //设置表格行的背景色，用于区分不同标度及重点关注病害
      setRowClassName(row) {
        if(!row.bridgeMemberId && !!row.memberTypeId) return "missing-row";
        if(row.isSignificant === 1) return "significant-row";
        if(row.deductionScale) {
          switch (row.deductionScale) {
            case 3:
              return "info-row";
            case 4:
              return "warning-row";
            case 5:
              return "danger-row";
          }
        }
        return "";
      },
      //检测方向更改
      handleDirectionChange() {
        this.fetchBridgeDiseaseData();
      },
      //新增桥梁整体情况
      handleBridgeConditionAdd() {
        this.bridgeConditionForm = {...this.queryParam, notes:""};
        this.isBridgeConditionDialogVisible = true;
        this.bridgeConditionUpdateType = ADD;
        //初始化表单校验结果
        if(this.$refs[BRIDGE_CONDITION_FORM]) this.$refs[BRIDGE_CONDITION_FORM].resetFields();
      },
      //桥梁整体情况记录修改
      handleBridgeConditionEdit(data) {
        this.bridgeConditionUpdateType = EDIT;
        this.bridgeConditionForm = {...data};
        this.isBridgeConditionDialogVisible = true;
        //初始化表单校验结果
        if(this.$refs[BRIDGE_CONDITION_FORM]) this.$refs[BRIDGE_CONDITION_FORM].resetFields();
      },
      //删除一条记录
      handleDelete(data) {
        this.$confirm("此操作将永久删除该条数据, 是否继续?", "提示", {
          confirmButtonText:"确定",
          cancelButtonText:"取消",
          type:"warning"
        }).then(()=>{
          doDelete(this.rootUrl + DELETE_URL, {
            data,
            menuFunctionId:getAuthorizedFunction(this, DELETE),
            component:this
          })
            .then(response => {
              this.$message({message:response.message, type:response.status.toLowerCase()});
              //重新加载桥梁整体状况记录表及病害表
              this.fetchData();
            });
        });
      },
      //处理桥梁孔跨情况新增事件
      handleBridgeSiteConditionAdd() {
        this.diseaseUpdateType = ADD;
        this.justSite = true;
        this.initDiseaseForm();
        this.isDiseaseDialogVisible = true;
      },
      //处理病害新增事件，传入正在记录的部位名称，如'上部结构'、'下部结构'等
      handleDiseaseAdd(recordPosition) {
        //设置对话框处于新增状态
        this.diseaseUpdateType = ADD;
        this.diseaseDialogTitle = "新增";
        this.justSite = false;
        //初始化病害表单，先清除所有属性的值，然后设置选中孔号、任务单、分幅等，同时将表单的描述控件设为隐藏
        this.initDiseaseForm();
        //打开对话框
        this.isDiseaseDialogVisible = true;
        //设置当前记录的部位
        this.recordPosition = recordPosition;
        //获取对应的部件数据
        this.fetchPartsData(!!this.diseaseForm.siteNo?this.diseaseForm.siteNo:1);
      },
      //处理病害编辑事件
      handleDiseaseEdit(data) {
        //设置对话框为编辑状态
        this.diseaseUpdateType = EDIT;
        this.diseaseDialogTitle = "编辑";
        //初始化编辑用的表单对象，单位逆转换，给位置范围赋值等
        this.initDiseaseEditOrCopy(data);
        //打开对话框
        this.isDiseaseDialogVisible = true;
      },
      //处理病害复制事件
      handleDiseaseCopy(data) {
        //设置对话框为复制状态
        this.diseaseUpdateType = COPY;
        this.diseaseDialogTitle = "复制";
        //初始化复制用的表单对象，单位逆转换，给位置范围赋值等
        this.initDiseaseEditOrCopy(data);
        //打开对话框
        this.isDiseaseDialogVisible = true;
      },
      //处理孔跨切换事件
      handleSiteChange(siteNo) {
        //如果只是记录孔跨或者为表单编辑、复制事件，则不做任何处理
        if(!this.justSite && this.diseaseUpdateType === ADD) {
          //清空部件、构件、病害及病害描述
          this.clearDiseasePartsCascadeProps();
          //隐藏所有的病害描述表单项
          this.initDiseaseDescForm();
          //获取该孔的部件信息
          this.fetchPartsData(siteNo);
        }
      },
      //处理部件修改事件，先清空所有的构件、病害类型及病害描述
      handlePartsChange(bridgePartsId) {
        //清除之前选中的构件编号、病害类型及描述方式
        this.clearDiseaseMemberCascadeProps();
        //隐藏所有的病害描述表单项
        this.initDiseaseDescForm();
        //判断部件是否存在，不存在也没必要进行下一步了
        let bridgeParts = this.bridgePartsList.filter(item=>item.id === bridgePartsId)[0];
        if(bridgeParts) {
          //赋予病害表单部件类型
          this.diseaseForm.partsTypeId = bridgeParts.partsTypeId;
          this.diseaseForm.memberTypeId = bridgeParts.memberTypeId;
          this.diseaseForm.materialTypeId = bridgeParts.materialTypeId;
          //获取对应数据
          this.fetchMemberData(bridgeParts.memberTypeId);
          this.fetchDiseaseTypeData(bridgeParts.materialTypeId, bridgeParts.memberTypeId);
        }else {
          //如果部件不存在，则清除所有级联的数据
          this.clearDiseasePartsCascadeProps();
        }
      },
      //处理构件修改事件
      handleMemberChange(bridgeMemberId) {
        //清除病害构件编号相关的属性
        this.clearDiseaseMemberNoCascadeProps();
        //赋予病害表单构件编号相关参数
        let bridgeMember = this.bridgeMemberList.filter(item=>item.id === bridgeMemberId)[0];
        if (bridgeMember) {
          this.diseaseForm.memberHorizontalNo = bridgeMember.horizontalNo;
          this.diseaseForm.memberVerticalNo = bridgeMember.verticalNo;
          this.diseaseForm.memberStakeSide = bridgeMember.stakeSide;
          this.diseaseForm.memberSpecialSection = bridgeMember.specialSection;
        }
      },
      //处理病害修改事件
      handleDiseaseChange(diseaseTypeId) {
        //清除病害描述级联属性
        this.clearDiseaseDescCascadeProps();
        //隐藏所有的病害描述表单项
        this.initDiseaseDescForm();
        //设置当前正在记录的病害
        this.recordDiseaseType = this.diseaseTypeList.filter(item=>item.id === diseaseTypeId)[0];
        if(this.recordDiseaseType) {
          //判断已经选择的病害标度是否还适用
          if(!this.recordDiseaseType.maxScale || this.recordDiseaseType.maxScale < this.diseaseForm.deductionScale) this.diseaseForm.deductionScale = "";
          //获取选中病害的描述方式集合
          this.diseaseDescList = this.recordDiseaseType.diseaseDescList;
          if(this.diseaseForm.diseaseDescId) {
            if(this.diseaseDescList.some(item=>item.id === this.diseaseForm.diseaseDescId)) {
              this.handleDiseaseDescChange(this.diseaseForm.diseaseDescId);
            } else {
              this.diseaseForm.diseaseDescId = "";
            }
          }
        }
      },
      //处理病害描述修改事件
      handleDiseaseDescChange(diseaseDescId) {
        this.diseaseForm.diseaseDescId = diseaseDescId;
        //赋予病害描述相关参数
        let diseaseDescType = this.diseaseDescList.filter(item=>item.id === diseaseDescId)[0];
        if(diseaseDescType) {
          this.diseaseForm.diseaseDesc = diseaseDescType.diseaseDesc;
          this.generateDiseaseDescForm();
          this.fetchMemberPositionData();
          this.fetchDescDegreeList();
        }
      },
      showEvaluationDetail() {
        this.isEvaluationDetailDialogVisible = true;
        this.loadingEvaluationTable = true;
        this.evaluationDetail = [];
        doGet(this.rootUrl + EVALUATION_DETAIL_URL, {
          data:{
            bridgeId:this.currentSide.bridgeId,
            sideTypeId:this.currentSide.sideTypeId,
            taskId:this.currentTask.id,
            direction:this.direction
          }
        })
          .then(response=>this.evaluationDetail = response)
          .finally(()=> this.loadingEvaluationTable = false)
      },
      //评分调整对话框显示
      handlePointAdjustment() {
        this.isAdjustPointDialogVisible = true;
      },
      adjustPoint() {
        this.evaluate();
        this.isAdjustPointDialogVisible = false;
      },
      //桥梁评定
      evaluate() {
        this.evaluating = true;
        doPost(this.rootUrl + BRIDGE_EVALUATION_URL, {
          data:{
            bridgeId:this.currentSide.bridgeId,
            sideTypeId:this.currentSide.sideTypeId,
            taskId:this.currentTask.id,
            evaluationType:this.evaluationType
          },
          menuFunctionId:getAuthorizedFunction(this, MANAGE),
          component:this
        }).then(response=>{
          if(Array.isArray(response) && response.length>0) {
            this.bridgeEvaluation = response[0];
            this.evaluationType = response[0].evaluationType;
            for(let i=1; i<response.length; i++) {
              if (this.bridgeEvaluation.sideLevel < response[i].sideLevel) {
                this.bridgeEvaluation = response[i];
              } else if (this.bridgeEvaluation.sideLevel === response[i].sideLevel && this.bridgeEvaluation.sidePoint > response[i].sidePoint) {
                  this.bridgeEvaluation = response[i];
              }
            }
          }else {
            this.bridgeEvaluation.sidePoint = "尚未评定";
            this.bridgeEvaluation.sideLevel = "尚未评定";
          }
        }).finally(()=>this.evaluating = false);
      },
      //更新桥梁病害
      updateBridgeDisease() {
        this.$refs[DISEASE_FORM].validate(valid=>{
          if(valid) {
            this.isBridgeDiseaseUpdating = true;
            //获取病害的扣分值，未选扣分标度的默认为标度2
            if(!!this.recordDiseaseType.maxScale) {
              if (!this.diseaseForm.deductionScale) this.diseaseForm.deductionScale = 2;
              this.diseaseForm.deductionPoint = getDeductionPoint(this.diseaseForm.deductionScale, this.recordDiseaseType.maxScale);
            }
            //尺寸单位全部转化为mm
            this.convertDiseaseFormUnit();
            //清除不要的字段数据
            this.clearUselessDiseaseProp();
            //判断病害是否重复
            if(this.isDiseaseDuplication()) {
              this.$alert("病害重复，请核查！", "提示");
              this.isBridgeDiseaseUpdating = false;
            } else {
              //确定表单操作的地址
              let url = ADD_DISEASE_URL;
              if(this.diseaseUpdateType === EDIT) url = EDIT_DISEASE_URL;
              //发送数据至服务端
              doPost(this.rootUrl + url, {
                data:this.diseaseForm,
                menuFunctionId:getAuthorizedFunction(this, this.diseaseUpdateType),
                component:this
              }).then(response=>{
                this.isDiseaseDialogVisible = false;
                this.$message({message:response.message, type:response.status.toLowerCase()});
              }).finally(()=>{
                this.isBridgeDiseaseUpdating = false;
                this.fetchData();
              });
            }
          }
        });
      },
      //更新桥梁整体情况记录
      updateBridgeCondition() {
        this.$refs[BRIDGE_CONDITION_FORM].validate(valid=> {
          if (valid) {
            this.isBridgeConditionUpdating = true;
            doPost(this.rootUrl + (this.bridgeConditionUpdateType === ADD?ADD_DISEASE_URL:EDIT_DISEASE_URL), {
              data: this.bridgeConditionForm,
              menuFunctionId:getAuthorizedFunction(this, this.bridgeConditionUpdateType),
              component: this
            })
              .then(response => this.$message({message: response.message, type: response.status.toLowerCase()}))
              .finally(()=>{
                this.isBridgeConditionUpdating = false;
                this.isBridgeConditionDialogVisible = false;
                this.fetchBridgeConditionData();
              });
          }
        });
      },
      //获取桥梁整体情况记录缩写
      getBridgeConditionIntro(notes) {
        if(notes !== null) {
          if (notes.length < BRIDGE_CONDITION_TITLE_SIZE) return notes;
          else return notes.substr(0, BRIDGE_CONDITION_TITLE_SIZE) + "...";
        }
      },
      //初始化病害表单，先清除所有属性的值，然后设置孔号、任务单、分幅等，同时将表单的描述控件设为隐藏
      initDiseaseForm() {
        //初始化表单对象
        clearFields(this.diseaseForm);
        //设置选中的孔号
        this.diseaseForm.siteNo = this.selectedNode.siteNo;
        //赋予病害表单相关控制参数
        this.diseaseForm.taskId = this.currentTask.id;
        this.diseaseForm.bridgeId = this.currentSide.bridgeId;
        this.diseaseForm.sideTypeId = this.currentSide.sideTypeId;
        //初始化病害描述参数
        this.initDiseaseDescForm();
      },
      //将病害表单中的尺寸单位转换为mm
      convertDiseaseFormUnit() {
        this.diseaseForm.minLength = this.toMMValue(this.diseaseForm._minLength, MIN_LENGTH);
        this.diseaseForm.maxLength = this.toMMValue(this.diseaseForm._maxLength, MAX_LENGTH);
        this.diseaseForm.minWidth = this.toMMValue(this.diseaseForm._minWidth, MIN_WIDTH);
        this.diseaseForm.maxWidth = this.toMMValue(this.diseaseForm._maxWidth, MAX_WIDTH);
        this.diseaseForm.minDepth = this.toMMValue(this.diseaseForm._minDepth, MIN_DEPTH);
        this.diseaseForm.maxDepth = this.toMMValue(this.diseaseForm._maxDepth, MAX_DEPTH);
      },
      //将病害表单中的尺寸单位由初始的mm转化为原单位
      reverseDiseaseFormUnit() {
        this.diseaseForm._minLength = convertUnit(this.diseaseForm.minLength, MM, this.parseUnit(MIN_LENGTH));
        this.diseaseForm._maxLength = convertUnit(this.diseaseForm.maxLength, MM, this.parseUnit(MAX_LENGTH));
        this.diseaseForm._minWidth = convertUnit(this.diseaseForm.minWidth, MM, this.parseUnit(MIN_WIDTH));
        this.diseaseForm._maxWidth = convertUnit(this.diseaseForm.maxWidth, MM, this.parseUnit(MAX_WIDTH));
        this.diseaseForm._minDepth = convertUnit(this.diseaseForm.minDepth, MM, this.parseUnit(MIN_DEPTH));
        this.diseaseForm.__maxDepth = convertUnit(this.diseaseForm.maxDepth, MM, this.parseUnit(MAX_DEPTH));
      },
      //隐藏所有的表单
      initDiseaseDescForm() {
        Object.keys(this.diseaseDescParam).forEach(prop=>this.diseaseDescParam[prop] = false);
      },
      //初始化表单编辑或复制事件
      initDiseaseEditOrCopy(data) {
        //初始化表单
        this.initDiseaseForm();
        //复制给病害表单，必须加上三个位置范围，否则拖动条会不正常
        this.diseaseForm = {...data, bridgeMemberIds:[]};
        //判断是不是孔跨编辑
        if(!data.positionTypeName && !data.partsTypeId && !data.memberTypeId) {
          //设置为孔跨视图
          this.justSite = true;
        } else {
          //设置为病害视图
          this.justSite = false;
          //单位还原
          this.reverseDiseaseFormUnit();
          //获取必要的表单数据
          this.recordPosition = data.positionTypeName;
          this.fetchPartsData(data.siteNo);
          this.generateDiseaseDescForm();
        }
      },
      generateDiseaseDescForm() {
        if (this.diseaseForm.diseaseDesc) {
          this.diseaseDescParam.containHPosition = this.diseaseForm.diseaseDesc.includes(H_POSITION_START);
          this.diseaseDescParam.containHPositionRange = this.diseaseForm.diseaseDesc.includes(H_POSITION_END);
          this.diseaseDescParam.containLPosition = this.diseaseForm.diseaseDesc.includes(L_POSITION_START);
          this.diseaseDescParam.containLPositionRange = this.diseaseForm.diseaseDesc.includes(L_POSITION_END);
          this.diseaseDescParam.containVPosition = this.diseaseForm.diseaseDesc.includes(V_POSITION_START);
          this.diseaseDescParam.containVPositionRange = this.diseaseForm.diseaseDesc.includes(V_POSITION_END);
          this.diseaseDescParam.containPosition = this.diseaseForm.diseaseDesc.includes(POSITION);
          this.diseaseDescParam.containCount = this.diseaseForm.diseaseDesc.includes(COUNT);
          this.diseaseDescParam.containAngle = this.diseaseForm.diseaseDesc.includes(ANGLE);
          this.diseaseDescParam.containMinLength = this.diseaseForm.diseaseDesc.includes(MIN_LENGTH);
          this.diseaseDescParam.containMaxLength = this.diseaseForm.diseaseDesc.includes(MAX_LENGTH);
          this.diseaseDescParam.containMinWidth = this.diseaseForm.diseaseDesc.includes(MIN_WIDTH);
          this.diseaseDescParam.containMaxWidth = this.diseaseForm.diseaseDesc.includes(MAX_WIDTH);
          this.diseaseDescParam.containMinDepth = this.diseaseForm.diseaseDesc.includes(MIN_DEPTH);
          this.diseaseDescParam.containMaxDepth = this.diseaseForm.diseaseDesc.includes(MAX_DEPTH);
          this.diseaseDescParam.containPercentDegree = this.diseaseForm.diseaseDesc.includes(PERCENT_DEGREE);
          this.diseaseDescParam.containDescDegree = this.diseaseForm.diseaseDesc.includes(DESC_DEGREE);
          this.diseaseDescParam.containBehaviorDesc = this.diseaseForm.diseaseDesc.includes(BEHAVIOR_DESC);
        }
      },
      //清空病害表单中部件级联的属性
      clearDiseasePartsCascadeProps() {
        //清空部件、构件、病害及病害描述等
        if(this.diseaseUpdateType === ADD) {
          this.diseaseForm.bridgePartsId = "";
          this.diseaseForm.bridgeMemberId = "";
          this.diseaseForm.bridgeMemberIds = [];
          this.diseaseForm.diseaseTypeId = "";
          this.diseaseForm.diseaseDescId = "";
        }
        this.diseaseForm.partsTypeId = "";
        this.diseaseForm.memberTypeId = "";
        this.diseaseForm.memberHorizontalNo = "";
        this.diseaseForm.memberVerticalNo = "";
        this.diseaseForm.memberStakeSide = "";
        this.diseaseForm.memberSpecialSection = "";
        this.diseaseForm.materialTypeId = "";
        this.diseaseForm.diseaseDesc = "";
        //清空表单可选项
        this.bridgePartsList = [];
        this.bridgeMemberList = [];
        this.diseaseTypeList = [];
        this.diseaseDescList = [];
      },
      //清除病害表单中构件级联的属性
      clearDiseaseMemberCascadeProps() {
        if(this.diseaseUpdateType === ADD) {
          this.diseaseForm.bridgeMemberId = "";
          this.diseaseForm.bridgeMemberIds = [];
          this.diseaseForm.diseaseTypeId = "";
          this.diseaseForm.diseaseDescId = "";
        }
        this.diseaseForm.memberTypeId = "";
        this.diseaseForm.memberHorizontalNo = "";
        this.diseaseForm.memberVerticalNo = "";
        this.diseaseForm.memberStakeSide = "";
        this.diseaseForm.memberSpecialSection = "";
        this.diseaseForm.materialTypeId = "";
        this.diseaseForm.diseaseDesc = "";
        this.bridgeMemberList = [];
        this.diseaseTypeList = [];
        this.diseaseDescList = [];
      },
      //清除病害表单中构件编号级联的属性
      clearDiseaseMemberNoCascadeProps() {
        this.diseaseForm.memberHorizontalNo = "";
        this.diseaseForm.memberVerticalNo = "";
        this.diseaseForm.memberStakeSide = "";
        this.diseaseForm.memberSpecialSection = "";
      },
      //清除构件描述级联的属性
      clearDiseaseDescCascadeProps() {
        if(this.diseaseUpdateType === ADD) {
          this.diseaseForm.diseaseDescId = "";
        }
        this.diseaseForm.diseaseDesc = "";
        this.diseaseDescList = [];
      },
      //清除改病害类型中不存在的病害参数，防止保存不该保存的字段
      clearUselessDiseaseProp() {
        if(!this.diseaseDescParam.containHPosition) this.diseaseForm.hPositionStart = null;
        if(!this.diseaseDescParam.containHPositionRange) this.diseaseForm.hPositionEnd = null;
        if(!this.diseaseDescParam.containLPosition) this.diseaseForm.lPositionStart = null;
        if(!this.diseaseDescParam.containLPositionRange) this.diseaseForm.lPositionEnd = null;
        if(!this.diseaseDescParam.containVPosition) this.diseaseForm.vPositionStart = null;
        if(!this.diseaseDescParam.containVPositionRange) this.diseaseForm.vPositionEnd = null;
        if(!this.diseaseDescParam.containPosition) this.diseaseForm.position = null;
        if(!this.diseaseDescParam.containCount) this.diseaseForm.count = null;
        if(!this.diseaseDescParam.containAngle) this.diseaseForm.angle = null;
        if(!this.diseaseDescParam.containMinLength) this.diseaseForm.minLength = null;
        if(!this.diseaseDescParam.containMaxLength) this.diseaseForm.maxLength = null;
        if(!this.diseaseDescParam.containMinWidth) this.diseaseForm.minWidth = null;
        if(!this.diseaseDescParam.containMaxWidth) this.diseaseForm.maxWidth = null;
        if(!this.diseaseDescParam.containMinDepth) this.diseaseForm.minDepth = null;
        if(!this.diseaseDescParam.containMaxDepth) this.diseaseForm.maxDepth = null;
        if(!this.diseaseDescParam.containPercentDegree) this.diseaseForm.percentDegree = null;
        if(!this.diseaseDescParam.containDescDegree) this.diseaseForm.descDegree = null;
        if(!this.diseaseDescParam.containBehaviorDesc) this.diseaseForm.behaviorDesc = null;
        //判断是否可以进行扣分，这里可能记录的是孔跨整体情况
        if(!this.diseaseForm.diseaseTypeId && !this.diseaseForm.memberTypeId) {
          this.diseaseForm.deductionScale = null;
          this.diseaseForm.deductionPoint = null;
        }
      },
      //解析对应属性的尺寸单位
      parseUnit(prop) {
        if(!this.diseaseForm.diseaseDesc) return "";
        let pattern = new RegExp("\\{"+prop+",([^\\{\\}]*?)\\}");
        let matches = pattern.exec(this.diseaseForm.diseaseDesc);
        if(matches) {
          return matches[1];
        }else {
          return "";
        }
      },
      //转化为mm值
      toMMValue(value, prop) {
        return convertUnit(value, this.parseUnit(prop), MM)
      },
      //判断病害是否重复
      isDiseaseDuplication() {
        if(this.diseasePageData.data && this.diseasePageData.data.length > 0) {
          if(this.justSite) {
            return this.diseasePageData.data.some(item=>equals(item.siteNo, this.diseaseForm.siteNo) && equals(item.notes, this.diseaseForm.notes));
          } else {
            return this.diseasePageData.data.some(item => {
              //先判断构件是否属于同一个构件
              if(!this.diseaseForm.bridgeMemberIds.includes(item.bridgeMemberId)) return false;
              if(!this.diseaseForm.bridgeMemberId === item.bridgeMemberId) return false;
              //再判断病害的参数是否相同
              return equals(item.siteNo, this.diseaseForm.siteNo)
                && equals(item.diseaseTypeId, this.diseaseForm.diseaseTypeId)
                && equals(item.hPositionStart, this.diseaseForm.hPositionStart)
                && equals(item.hPositionEnd, this.diseaseForm.hPositionEnd)
                && equals(item.lPositionStart, this.diseaseForm.lPositionStart)
                && equals(item.lPositionEnd, this.diseaseForm.lPositionEnd)
                && equals(item.vPositionStart, this.diseaseForm.vPositionStart)
                && equals(item.vPositionEnd, this.diseaseForm.vPositionEnd)
                && equals(item.position, this.diseaseForm.position)
                && equals(item.count, this.diseaseForm.count)
                && equals(item.angle, this.diseaseForm.angle)
                && equals(item.minLength, this.diseaseForm.minLength)
                && equals(item.maxLength, this.diseaseForm.maxLength)
                && equals(item.minWidth, this.diseaseForm.minWidth)
                && equals(item.maxWidth, this.diseaseForm.maxWidth)
                && equals(item.minDepth, this.diseaseForm.minDepth)
                && equals(item.maxDepth, this.diseaseForm.maxDepth)
                && equals(item.percentDegree, this.diseaseForm.percentDegree)
                && equals(item.descDegree, this.diseaseForm.descDegree)
                && equals(item.behaviorDesc, this.diseaseForm.behaviorDesc)
                && equals(item.notes, this.diseaseForm.notes)
                && (this.diseaseUpdateType !== EDIT && equals(item.isSignificant, this.diseaseForm.isSignificant))
                && (this.diseaseUpdateType !== EDIT && equals(item.deductionScale, this.diseaseForm.deductionScale))
            });
          }
        } else {
          return false;
        }
      },
      //获取孔跨数据，获取数据同时显示加载框
      fetchSiteData() {
        this.isTreeLoading = true;
        doGet(this.rootUrl + "/getDiseaseSiteList", {
          data: this.queryParam,
          component: this
        })
          .then(response =>this.siteList = response)
          .finally(()=>this.isTreeLoading = false);
      },
      //获取桥梁整体状况数据列表
      fetchBridgeConditionData() {
        doGet(this.rootUrl + "/getBridgeConditionList", {
          data:this.queryParam,
          component:this
        }).then(response=>this.bridgeConditionList = response);
      },
      //获取病害数据
      fetchBridgeDiseaseData() {
        this.isTableLoading = true;
        doGet(this.rootUrl + "/getBridgeDiseaseList", {
          data:this.queryParam,
          component:this
        })
          .then(response=>this.diseasePageData.data = response)
          .finally(()=>this.isTableLoading = false);
      },
      //获取部件数据，如果病害表单原本有部件ID，则触发部件变动事件
      fetchPartsData(siteNo) {
        let uri = "";
        switch (this.recordPosition) {
          case SUPER:
            uri = "/getSuperPartsBySiteNo";
            break;
          case SUB:
            uri = "/getSubPartsBySiteNo";
            break;
          case DECK:
            uri = "/getDeckPartsBySiteNo";
            break;
        }
        this.isDiseaseFormLoading = true;
        doGet(this.rootUrl + uri, {
          data:{bridgeId:this.currentSide.bridgeId,
            sideTypeId:this.currentSide.sideTypeId,
            siteNo},
          component:this
        })
          .then(response=>this.bridgePartsList = response)
          .finally(()=>{
            this.isDiseaseFormLoading = false;
            //触发部件变动事件，获取构件编号及病害类型，如果没有部件类型，则清空所有之前选择的数据
            if(this.diseaseForm.bridgePartsId) {
              this.handlePartsChange(this.diseaseForm.bridgePartsId);
            } else {
              this.diseaseForm.bridgePartsId = "";
              this.diseaseForm.bridgeMemberId = "";
              this.diseaseForm.bridgeMemberIds = [];
              this.diseaseForm.diseaseTypeId = "";
              this.diseaseForm.diseaseDescId = "";
            }
          });
      },
      //获取构件数据，如果原本有构件，则触发构件变动事件，将构件相关编号属性赋予病害表单对象
      fetchMemberData(memberTypeId) {
        this.isDiseaseFormLoading = true;
        doGet(this.rootUrl + "/getBridgeMemberList", {
          data:{
            direction:this.direction,
            bridgeId:this.currentSide.bridgeId,
            sideTypeId:this.currentSide.sideTypeId,
            siteNo:this.diseaseForm.siteNo,
            memberTypeId
          },
          component:this
        })
          .then(response=>this.bridgeMemberList = response)
          .finally(()=>{
            this.isDiseaseFormLoading = false;
            if(this.diseaseForm.bridgeMemberId) {
              if(this.bridgeMemberList.some(item=>item.id === this.diseaseForm.bridgeMemberId)) {
                this.handleMemberChange(this.diseaseForm.bridgeMemberId);
              }else {
                this.diseaseForm.bridgeMemberId = "";
              }
            }
          });
      },
      //获取病害类型数据，如果原本有病害类型，则触发病害变动事件，获取病害描述数据
      fetchDiseaseTypeData(materialTypeId, memberTypeId) {
        this.isDiseaseFormLoading = true;
        let param = {memberTypeId};
        if(!!materialTypeId) param.materialTypeId = materialTypeId;
        doGet(this.rootUrl + "/getDiseaseTypeList", {
          data:param,
          component:this
        })
          .then(response=>this.diseaseTypeList = response)
          .finally(()=>{
            this.isDiseaseFormLoading = false;
            if(this.diseaseForm.diseaseTypeId) {
              if(this.diseaseTypeList.some(item=>item.id === this.diseaseForm.diseaseTypeId)) {
                this.handleDiseaseChange(this.diseaseForm.diseaseTypeId);
              }else {
                this.diseaseForm.diseaseTypeId = "";
                this.diseaseForm.diseaseDescId = "";
                this.diseaseForm.deductionScale = "";
              }
            }
          });
      },
      //获取构件位置下拉菜单数据
      fetchMemberPositionData() {
        if(this.diseaseDescParam.containPosition) {
          doGet(this.rootUrl + "/getMemberPositionList", {component: this}).then(response=>this.memberPositionList = response);
        }
      },
      //获取程度描述列表
      fetchDescDegreeList() {
        if (this.diseaseDescParam.containDescDegree) {
          doGet(this.rootUrl + "/getDescDegreeList", {component:this}).then(response=>this.descDegreeList = response);
        }
      },
      //页面初始化时加载的几个数据
      fetchData() {
        this.fetchSiteData();
        this.fetchBridgeConditionData();
        this.fetchBridgeDiseaseData();
        this.evaluate();
      },

      /** 生成评定详表对象 */
      mixEvaluationDto,

      //分数转换为等级
      pointToLevel
    },
    //启动时主动获取数据
    created() {
      this.fetchData();
    },
    //激活时重新获取数据
    activated() {
      this.fetchData();
    },
    //用到的两个组件
    components:{Table, DiseasePhotoWall}
  }
</script>

<style>
  .tree-view-scrollable-middle {
    max-height: 400px;
    border: 0;
  }
  .color-tip {
    display: inline-block;
    font-size: 0.5em;
    color: #ffffff;
    width: 60px;
    height: 22px;
    text-align: center;
    line-height: 20px;
    border: 1px solid transparent;
    border-radius: 4px;
    overflow: hidden;
    position: relative;
    margin: 5px 4px 0 0;
  }
  .color-tip.title {
    width: 65px;
    color: #000;
    font-weight: bold;
  }
  .color-tip.missing, .el-table .missing-row {
    background-color: gray;
  }
  .color-tip.info-row, .el-table .info-row {
    background-color: #58B7FF
  }
  .color-tip.warning-row, .el-table .warning-row {
    background-color: orange;
  }
  .color-tip.danger-row, .el-table .danger-row {
    background-color: #FF4949;
  }
  .color-tip.significant-row, .el-table .significant-row {
    background-color: green;
  }
</style>



// WEBPACK FOOTER //
// TaskBridgeDisease.vue?d60b1da4
